package com.yzt.message;

import android.text.TextUtils;

import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

import io.rong.imkit.conversationlist.model.BaseUiConversation;
import io.rong.imlib.model.Conversation;

/**
 * 未回复消息的工具处理类
 */
public class UnReplyMessageUtils {

    /**
     * 未读消息时间计算
     */
    private static final long unReplySeconds = 6 * 60 * 60 * 1000;

    private static final CopyOnWriteArrayList<BaseUiConversation> unReplyMessageList = new CopyOnWriteArrayList<>();

    //本地记录的消息扩展，为了防止多次异步
    private static final Map<String, MessageExtraInfo> messageExtra = new Hashtable<>();

    public static void addMessageExtra(String targetId, MessageExtraInfo messageExtra) {
        UnReplyMessageUtils.messageExtra.put(targetId, messageExtra);
    }

    public static void removeMessageExtra(String targetId) {
        UnReplyMessageUtils.messageExtra.remove(targetId);
    }

    public static boolean isMessageContent(String targetId, int messageId) {
        try {
            if (TextUtils.isEmpty(targetId)) {
                return false;
            }
            if (messageExtra.containsKey(targetId)) {
                MessageExtraInfo messageExtraInfo = messageExtra.get(targetId);
                if (messageExtraInfo.getLatestMessageId() == messageId) {
                    return true;
                } else {
                    //如果不一样，先快速置空
                    UnReplyMessageUtils.removeMessageExtra(targetId);
                }
            }
        } catch (Exception ignored) {

        }
        return false;
    }

    public static MessageExtraInfo getMessageContent(String targetId) {
        try {
            if (TextUtils.isEmpty(targetId)) {
                return null;
            }
            if (messageExtra.containsKey(targetId)) {
                return messageExtra.get(targetId);
            }
        } catch (Exception ignored) {

        }
        return null;
    }

    public static CopyOnWriteArrayList<BaseUiConversation> getUnReplyMessageList() {
        return unReplyMessageList;
    }

    public static void clearUnReplyMessageList() {
        unReplyMessageList.clear();
    }

    public static void setUnReplyMessageList(List<BaseUiConversation> messages) {
        unReplyMessageList.clear();
        unReplyMessageList.addAll(messages);
    }

    /**
     * 未读消息数量获取
     */
    public static int getUnreadMessageCount() {
        int unreadMessageCount = 0;
        for (BaseUiConversation uiConversation : unReplyMessageList) {
            unreadMessageCount += uiConversation.mCore.getUnreadMessageCount();
        }
        return unreadMessageCount;
    }

    public static boolean isUnReplyMessage(Conversation conversation) {
        //未回复消息时间达到指定时间
        return (System.currentTimeMillis() - conversation.getSentTime()) > unReplySeconds;
    }
}
